package com.google.code.sip.ucenter.dao.mongo.benchmark;

import java.util.concurrent.CyclicBarrier;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.google.code.sip.ucenter.benchmark.BenchmarkUtils;
import com.google.code.sip.ucenter.dao.BaseMongoTest;
import com.google.code.sip.ucenter.dao.mongo.CreditLogDaoImpl;

public class MongoBenchmark extends BaseMongoTest {
	private static CreditLogDaoImpl dao = new CreditLogDaoImpl();
	public final int[] THREADS = { 50 };

	@BeforeClass
	public static void beforeTest() throws Exception {
		init();
		dao.setMongoFactory(mongoFactory);
	}

	@Test
	public void write() {
		dao.clear();
		for (int i = 0; i < THREADS.length; i++) {
			int threads = THREADS[i];
			CyclicBarrier barrier = new CyclicBarrier(threads + 1);
			int repeats = 2;
			int countMax = 10000;
			for (int thread = 0; thread < threads; thread++) {
				new WriteBenchmarkThread(thread, dao, barrier, repeats,
						countMax).start();
			}
			try {
				barrier.await();
				long start = System.nanoTime();
				barrier.await();
				long duration = System.nanoTime() - start;
				BenchmarkUtils.printResult(threads, repeats, countMax, duration);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Test
	public void read() {
		for (int i = 0; i < THREADS.length; i++) {
			int threads = THREADS[i];
			CyclicBarrier barrier = new CyclicBarrier(threads + 1);
			int repeats = 2;
			int countMax = 10000;
			for (int thread = 0; thread < threads; thread++) {
				new ReadBenchmarkThread(thread, dao, barrier, repeats, countMax)
						.start();
			}
			try {
				barrier.await();
				long start = System.nanoTime();
				barrier.await();
				long duration = System.nanoTime() - start;
				BenchmarkUtils.printResult(threads, repeats, countMax, duration);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@AfterClass
	public static void clear() throws Exception {
		mongoFactory.destroy();
	}
}
